package com.lottery;

import java.util.*;

public class Main {
    private static Scanner scanner = new Scanner(System.in);

    public static void main(String[] args) {
        System.out.println("========== 双色球彩票系统 ==========");

        while (true) {
            showMenu();
            String choice = scanner.nextLine().trim();

            switch (choice) {
                case "1":
                    generateTickets();
                    break;
                case "2":
                    checkPrize();
                    break;
                case "3":
                    System.out.println("感谢使用双色球彩票系统，再见！");
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
            System.out.println();
        }
    }

    // 显示主菜单
    private static void showMenu() {
        System.out.println("请选择功能：");
        System.out.println("1. 生成5注彩票号码");
        System.out.println("2. 兑奖");
        System.out.println("3. 退出");
        System.out.print("请输入选择(1-3)：");
    }

    // 生成多注彩票号码
    private static void generateTickets() {
        System.out.print("请输入要生成的注数(默认5注)：");
        String input = scanner.nextLine().trim();
        int count = 5;

        if (!input.isEmpty()) {
            try {
                count = Integer.parseInt(input);
                if (count < 1 || count > 100) {
                    System.out.println("注数应在1-100之间，使用默认值5注");
                    count = 5;
                }
            } catch (NumberFormatException e) {
                System.out.println("输入无效，使用默认值5注");
            }
        }

        System.out.println("\n为您生成 " + count + " 注双色球号码：");
        System.out.println("==================================");

        for (int i = 1; i <= count; i++) {
            int[] redBalls = generateRandomBalls(6, 33);
            int[] blueBalls = generateRandomBalls(1, 16);
            System.out.printf("第%2d注: %s + %02d%n",
                    i, formatBalls(redBalls), blueBalls[0]);
        }
        System.out.println("==================================");
        System.out.println("祝您好运！");
    }

    // 兑奖功能
    private static void checkPrize() {
        try {
            // 输入用户投注号码
            System.out.println("请输入您的双色球投注号码（6个红球+1个蓝球，空格分隔）：");
            System.out.print("例如: 01 05 12 18 26 33 09 --> ");
            String userInput = scanner.nextLine();

            int[] userRedBalls = new int[6];
            int userBlueBall = parseInput(userInput, userRedBalls);

            // 选择开奖号码输入方式
            System.out.println("\n请选择开奖号码来源：");
            System.out.println("1. 手动输入开奖号码");
            System.out.println("2. 随机生成开奖号码");
            System.out.print("请选择(1-2)：");
            String choice = scanner.nextLine().trim();

            int[] drawRedBalls;
            int drawBlueBall;

            if ("1".equals(choice)) {
                // 手动输入开奖号码
                System.out.println("请输入开奖号码（6个红球+1个蓝球，空格分隔）：");
                System.out.print("例如: 01 05 12 18 26 33 09 --> ");
                String drawInput = scanner.nextLine();

                int[] tempRedBalls = new int[6];
                drawBlueBall = parseInput(drawInput, tempRedBalls);
                drawRedBalls = tempRedBalls;
            } else {
                // 随机生成开奖号码
                drawRedBalls = generateRandomBalls(6, 33);
                drawBlueBall = generateRandomBalls(1, 16)[0];
                System.out.println("随机生成开奖号码...");
            }

            // 显示开奖结果
            System.out.println("\n========== 开奖结果 ==========");
            System.out.println("红球: " + formatBalls(drawRedBalls));
            System.out.println("蓝球: " + String.format("%02d", drawBlueBall));

            // 判断中奖等级
            int prizeLevel = LotteryChecker.checkPrizeLevel(userRedBalls, userBlueBall, drawRedBalls, drawBlueBall);

            // 显示用户号码和中奖结果
            System.out.println("\n========== 您的号码 ==========");
            System.out.println("红球: " + formatBalls(userRedBalls));
            System.out.println("蓝球: " + String.format("%02d", userBlueBall));

            System.out.println("\n========== 中奖结果 ==========");
            String prizeName = getPrizeName(prizeLevel);
            System.out.println("中奖等级: " + prizeName);

            if (prizeLevel > 0) {
                System.out.println("恭喜您中奖了！");
            } else {
                System.out.println("很遗憾，未中奖。再接再厉！");
            }

        } catch (IllegalArgumentException e) {
            System.out.println("输入错误：" + e.getMessage());
        } catch (Exception e) {
            System.out.println("发生错误：" + e.getMessage());
        }
    }

    // 解析用户输入并验证
    private static int parseInput(String input, int[] redBalls) throws IllegalArgumentException {
        String[] parts = input.split("\\s+");
        if (parts.length != 7) {
            throw new IllegalArgumentException("请确保输入包含6个红球和1个蓝球，总共7个号码。");
        }

        Set<Integer> redSet = new HashSet<>();
        for (int i = 0; i < 6; i++) {
            int redBall = Integer.parseInt(parts[i]);
            if (redBall < 1 || redBall > 33 || redSet.contains(redBall)) {
                throw new IllegalArgumentException("红球号码应为1–33且不重复。");
            }
            redBalls[i] = redBall;
            redSet.add(redBall);
        }

        int blueBall = Integer.parseInt(parts[6]);
        if (blueBall < 1 || blueBall > 16) {
            throw new IllegalArgumentException("蓝球号码应为1–16。");
        }

        return blueBall;
    }

    // 随机生成号码
    private static int[] generateRandomBalls(int count, int max) {
        Random random = new Random();
        Set<Integer> balls = new HashSet<>();
        while (balls.size() < count) {
            balls.add(random.nextInt(max) + 1);
        }
        int[] result = balls.stream().mapToInt(Integer::intValue).toArray();
        Arrays.sort(result);
        return result;
    }

    // 格式化号码输出
    private static String formatBalls(int[] balls) {
        StringBuilder sb = new StringBuilder();
        for (int ball : balls) {
            sb.append(String.format("%02d ", ball));
        }
        return sb.toString().trim();
    }

    // 获取对应中奖等级名称
    private static String getPrizeName(int prizeLevel) {
        return switch (prizeLevel) {
            case 1 -> "一等奖";
            case 2 -> "二等奖";
            case 3 -> "三等奖";
            case 4 -> "四等奖";
            case 5 -> "五等奖";
            case 6 -> "六等奖";
            default -> "未中奖";
        };
    }
}